package com.powernode.money.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.powernode.money.constant.Constants;
import com.powernode.money.model.User;
import com.powernode.money.service.RechargeRecordService;
import com.powernode.money.web.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class RechargeController {

    @Reference(interfaceClass = RechargeRecordService.class, version = "1.0.0")
    private RechargeRecordService rechargeRecordService;

    @RequestMapping("/loan/page/toRecharge")
    public String toRecharge() {
        return "toRecharge";
    }


    @RequestMapping("/loan/toRecharge")
    public void toRecharge(double rechargeMoney, HttpServletResponse resp, HttpSession session) throws AlipayApiException, IOException {
        //充值号（商家订单号）
        String rechargeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        //订单名称
        String subject = "recharge";
        //登录用户
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //添加充值记录
        rechargeRecordService.add(user.getId(), rechargeNo, rechargeMoney, subject);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //把订单参数封装到支付请求对象中
        String body = "{\"out_trade_no\":\"" + rechargeNo + "\","
                + "\"total_amount\":\"" + rechargeMoney + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
        System.out.println(body);
        alipayRequest.setBizContent(body);
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // result就是一个自提交表单
        // 客户端浏览器输出自提交表单
        resp.setContentType("text/html;utf-8");
        resp.getWriter().print(result);
    }

    @RequestMapping("/loan/page/payReturn")
    public String payReturn(String out_trade_no, HttpServletRequest request, Model model) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //根据商家订单号，查询支付结果
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            //设置请求参数
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"}");
            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            //分析JSON结果
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject queryResponse = jsonObject.getJSONObject("alipay_trade_query_response");
            if ("10000".equals(queryResponse.getString("code"))) {
                String status = queryResponse.getString("trade_status");
                if ("TRADE_SUCCESS".equals(status) || "TRADE_FINISHED".equals(status)) {
                    model.addAttribute("trade_msg", "支付成功");
                    //更新充值记录状态为充值成功，增加账号余额
                    rechargeRecordService.updateRechargeSuccess(out_trade_no);
                } else if ("TRADE_CLOSED".equals(status)) {
                    model.addAttribute("trade_msg", "支付失败");
                    //更充值记录状态为支付失败....
                } else {
                    model.addAttribute("trade_msg", "尚未支付");
                }
            } else {
                model.addAttribute("trade_msg", "查询失败");
            }
        } else {
            model.addAttribute("trade_msg", "验签失败");
        }
        return "toRechargeBack";
    }

}
